<?php

class ArticleController extends Controller
{
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	public function actionDetails($id)
	{
		$details = Article::model()->findByPk($id);

		// 浏览次数
		$articleCount = new ArticleCount();
		$count = $articleCount->find(array(
			'condition'=>'article_id='.$id,
			'select'=>'view_count',
		));
		if(!$count)
		{
			$articleCount->article_id = $id;
			$articleCount->view_count = 1;
			$articleCount->save();
		}
		else
		{
			$count->updateCounters(array('view_count'=>1));
		}

		// 文章标签
		if($details->article_tag)
		{
			$details->tags_str = '';
			$tags = Tags::model()->findAll(array(
				'select'=>'tag_name',
				'condition'=>"id in ($details->article_tag)"
			));
		}
		else
		{
			$tags = array();
		}

		// 文章导航
		$nav = Nav::model()->find(array(
			'select'=>'nav_name',
			'condition'=>'id='.$details->article_nav
		));

		// 文章评论
		$commentCount = Comment::model()->count('article_id='.$id);
		$comments = Comment::model()->findAll(array(
			'condition'=>'article_id='.$id
		));

		// 可能喜欢...
		$mayLikeArticle = Article::model()->findAll(array(
			'select'=>'id, article_title, article_thumbnail',
			'condition'=>"article_nav=$details->article_nav and id <> $details->id",
			'limit'=>4,
		));

		// 获取随机图文
		$randList = Article::model()->findAll(array(
			'select'=>'id,article_title, article_summary, article_thumbnail, article_date',
			'limit'=>4,
			'order'=>'rand()',
		));

		$details->article_nav = $nav->nav_name;
		$details->article_count = $count == null ? 0 : $count->view_count;

		$this->render('details', array(
			'details'=>$details,
			'tags'=>$tags,
			'commentModel'=> Comment::model(),
			'commentCount'=>$commentCount,
			'comments'=>$comments,
			'mayLikeArticle'=>$mayLikeArticle,
			'randList'=>$randList
		));
	}

	public function actionPostComment()
	{
		$commentModel = new Comment();

		$this->performAjaxValidation($commentModel);

		if(isset($_POST['Comment']))
		{
			$commentModel->attributes=$_POST['Comment'];

			if($commentModel->save())
				echo 1;
		}
	}

	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='comment-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
